<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>拖拽元素</title>
    <style>
      #box1 {
        position: absolute;
        height: 100px;
        width: 100px;
        background-color: red;
      }
    </style>
  </head>
  <body>
    <div id="box1"></div>

    <script>
      /*
        拖拽box1元素
        - 拖拽的流程：
            1. 当鼠标在被拖拽元素上按下时，开始拖拽onmousedown
            2. 当鼠标移动被拖拽元素跟随鼠标移动onmousemove
            3. 当鼠标松开时，被拖拽元素固定在当前位置onmouseup
        */

      var box1 = document.getElementById("box1");
      box1.onmousedown = function (event) {
        /*
        div的偏移量 鼠标.clientX - 元素.offsetLeft
        div的偏移量 鼠标.clientY - 元素.offsetTop
        */
        event = event || window.event;
        var ol = event.clientX - box1.offsetLeft;
        var ot = event.clientY - box1.offsetTop;

        document.onmousemove = function (event) {
          event = event || window.event;
          var left = event.clientX - ol;
          var top = event.clientY - ot;

          box1.style.left = left + "px";
          box1.style.top = top + "px";
        };

        document.onmouseup = function () {
          document.onmousemove = null;
          document.onmouseup = null;
        };
      };
    </script>
  </body>
</html>
